import time
from concurrent.futures import ThreadPoolExecutor, as_completed


def spider(delay):
    time.sleep(delay)
    print(f"task {delay} done")
    return delay


def thread_pool():
    with ThreadPoolExecutor(max_workers=3) as t:
        """
        提交3个任务到线程池
        """
        start_time = time.time()
        t1 = t.submit(spider, 1)
        t2 = t.submit(spider, 2)
        t3 = t.submit(spider, 3)
        print(f"task1 is down :{t1.done()}")
        print(f"task2 is down :{t2.done()}")
        print(f"task3 is down :{t3.done()}")

        time.sleep(2.5)
        print(f"task1 is down :{t1.done()}")
        print(f"task2 is down :{t2.done()}")
        print(f"task3 is down :{t3.done()}")

        time.sleep(0.6)
        print(f"task3 is down :{t3.done()}")
        end_time = time.time()
        print(f"线程池1 cost time: {round(end_time - start_time, 1)}")


""" 
task1 is down :False
task2 is down :False
task3 is down :False
task 1 done
task 2 done
task1 is down :True
task2 is down :True
task3 is down :False
task 3 done
task3 is down :True
"""


def thread_pool_2():
    with ThreadPoolExecutor(max_workers=3) as t:
        start_time = time.time()
        # 提交任务到线程池
        future_to_id = {t.submit(spider, delay): delay for delay in range(1, 4)}
        # 获取任务执行结果
        for future in as_completed(future_to_id):
            delay = future_to_id[future]
            try:
                data = future.result()
            except Exception as e:
                print(f"task {delay} generated an exception: {e}")
            else:
                print(f"task {delay} return: {data}")
        end_time = time.time()
        print(f"线程池2 cost time: {round(end_time - start_time, 1)}")


""" 
task 1 done
task 1 return: 1
task 2 done
task 2 return: 2
task 3 done
task 3 return: 3
线程池2 cost time: 3.0
"""

if __name__ == "__main__":
    thread_pool()
    thread_pool_2()
